<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-row>
        <el-col :span="4.5">
          <el-form-item label="项目编号" prop="projectCode">
            <el-select v-model="queryParams.projectCode" filterable placeholder="请输入或选择项目编号" style="width: 200px;">
              <el-option
                  v-for="item in projectOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 下拉框+模糊搜索 -->

        <el-col :span="5">
          <el-form-item label="直接费用名称" prop="directName" label-width="100px">
            <el-input
                v-model="queryParams.directName"
                placeholder="请输入直接费用名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>



      <!--<el-form-item label="项目编号" prop="projectCode">-->
      <!--  <el-input-->
      <!--    v-model="queryParams.projectCode"-->
      <!--    placeholder="请输入项目编号"-->
      <!--    clearable-->
      <!--    @keyup.enter="handleQuery"-->
      <!--  />-->
      <!--</el-form-item>-->

      <el-row>
        <el-col :span="4">
          <el-form-item label="创建人" prop="createBy">
            <el-input
                v-model="queryParams.createBy"
                placeholder="请输入创建人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="daterangeCreateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="更新人" prop="updateBy">
            <el-input
                v-model="queryParams.updateBy"
                placeholder="请输入更新人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="更新时间">
            <el-date-picker
                v-model="daterangeUpdateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:direct:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:direct:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:direct:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:direct:export']"
          v-if="false">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="directList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" prop="id" v-if="false" />
      <el-table-column align="center" prop="areaId" v-if="false" />
      <el-table-column label="直接费用名称" align="center" prop="directName" />
      <el-table-column label="项目编号" align="center" prop="projectCode" />

      <el-table-column label="合同额" align="center" prop="contractWithTax" />
      <el-table-column label="合同编号" align="center" prop="contractCode" />

      <!--<el-table-column label="施工借方发生额合计" align="center" prop="totalNoTax" />-->
      <el-table-column label="累计已发生成本（含税）" align="center" prop="realTotalWithTax" />
      <el-table-column label="实际进项税率" align="center" prop="taxRate" />
      <el-table-column label="税额" align="center" prop="tax" />

      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" sortable/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:direct:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:direct:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改直接费用对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="directRef" :model="form" :rules="rules" label-width="170px">
        <el-form-item label="直接费用名称" prop="directName">
          <el-input v-model="form.directName" placeholder="请输入直接费用名称" />
        </el-form-item>

        <!-- 下拉框+模糊搜索 -->
        <el-form-item label="项目编号" prop="projectCode" label-width="170px">
          <el-select v-model="form.projectCode" filterable placeholder="请输入或选择项目编号">
            <el-option
                v-for="item in projectOptions"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="合同额" prop="contractWithTax" label-width="170px">
          <el-input v-model="form.contractWithTax" placeholder="合同额" />
        </el-form-item>

        <el-form-item label="合同编号" prop="contractWithTax" label-width="170px">
          <el-input v-model="form.contractCode" placeholder="合同编号" />
        </el-form-item>

        <!--<el-form-item label="施工借方发生额" prop="totalNoTax">
          <el-input v-model="form.totalNoTax" placeholder="请输入施工借方发生额合计" />
        </el-form-item>-->
        <el-form-item label="累计已发生成本（含税）" prop="realTotalWithTax" label-width="170px">
          <el-input v-model="form.realTotalWithTax" placeholder="请输入累计已发生成本（含税）" />
        </el-form-item>
        <el-form-item label="实际进项税率" prop="taxRate" label-width="170px">
          <el-input v-model="form.taxRate" placeholder="请输入实际进项税率" />
        </el-form-item>

        <el-form-item label="供应商" prop="remark" label-width="170px">
          <el-input v-model="form.supplier" placeholder="请输入供应商" />
        </el-form-item>

        <el-form-item label="备注" prop="remark" label-width="170px">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Direct">
import { listDirect, getDirect, delDirect, addDirect, updateDirect } from "@/api/system/direct";

const { proxy } = getCurrentInstance();

const directList = ref([]);
const projectOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const daterangeUpdateTime = ref([]);

// 获取当前 URL 中的查询参数部分
const queryString = window.location.search;
// 使用 URLSearchParams 对象解析查询参数
const urlParams = new URLSearchParams(queryString);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    directName: null,
    projectCode: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    areaId: urlParams.get('areaId')
  },
  rules: {
    directName: [
      { required: true, message: "直接费用名称不能为空", trigger: "blur" }
    ],
    projectCode: [
      { required: true, message: "项目编号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询直接费用列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  console.log("areaId: " + queryParams.value.areaId);
  if (null != daterangeCreateTime && '' !== daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  if (null != daterangeUpdateTime && '' !== daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listDirect(queryParams.value).then(response => {
    directList.value = response.dataList.rows;
    projectOptions.value = response.projectCodeList;
    total.value = response.dataList.total;
    loading.value = false;
  });
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    directName: null,
    projectCode: null,
    realTotalWithTax: null,
    remark: null,
    tax: null,
    taxRate: null,
    totalNoTax: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("directRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  daterangeCreateTime.value = [];
  daterangeUpdateTime.value = [];
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.areaId = queryParams.value.areaId;
  open.value = true;
  title.value = "添加直接费用";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDirect(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改直接费用";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["directRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDirect(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDirect(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除直接费用编号为"' + _ids + '"的数据项？').then(function() {
    return delDirect(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/direct/export', {
    ...queryParams.value
  }, `direct_${new Date().getTime()}.xlsx`)
}

getList();
</script>
